package sweet.mvc.core

import scala.collection.{ mutable }
import sweet.helper._
import sweet.mvc.api._

/** abstract control to add controllers mappings */
trait ControllerContainer {
  // controllers
  def controllers = _controllers.readOnly
  protected val _controllers = new mutable.HashMap[String, Controller]
  
  /** Add controllers to the container. */
  def addControllers(tuples: (String, Controller)*){
    for((k,v) <- tuples) _controllers(k) = v
  }
  
  // interceptors
  def interceptors = _interceptors.readOnly
  protected val _interceptors = new mutable.HashMap[String, List[Interceptor]]
  
  /** Add a interceptor per each handlerNames in this controllerName */
  def addIntercepor(itc: Interceptor, controllerName: String, handlerNames: List[String]){
    val ctr = _controllers(controllerName)
    for(handlerName <- handlerNames){
      val name = controllerName+handlerName
      _interceptors(name) = itc :: _interceptors.getOrElse(name, Nil)
    }
  }
  
  /** Add a interceptor per all handlers in this controllerName minus the exceptionNames. */
  def addInterceptorWithExceptList(itc: Interceptor, controllerName: String, exceptionNames: List[String]){
    val ctr = _controllers(controllerName)
    val handlers = ctr.handlers.filter{ case (hk, hv)=> !exceptionNames.contains(hk) }
    for((handlerName, hv) <- handlers){
      val name = controllerName+handlerName
      _interceptors(name) = itc :: _interceptors.getOrElse(name, Nil)
    }
  }
}

/** abstract control to add layout templates mappings */
trait LayoutContainer {
  def layouts = _layouts.readOnly
  protected val _layouts = new mutable.HashMap[String, String]
  def addLayouts(tuples: (String, String)*){
    for((k,v) <- tuples) _layouts(k) = v
  }  
}
